package array;


import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 给定一个任意数组，找出数组中重复数字的个数
 */
public class FindRepeatCount {

  /**
   * 好几个重复的数字，多次重复的多次计数 如果只单纯统计重复的元素的个数，定义另一个set统计重复的数字
   */
  public int findRepeatCount(int array[]) {
    if (array == null || array.length <= 0) {
      System.out.println("数组为null或者数组的长度小于等于0");
      return -1;
    }

    Set<Integer> set = new HashSet<>();
    Set countSet = new HashSet<>();
    int count = 0;
    for (int i = 0; i < array.length; i++) {
      if (set.contains(array[i])) {
        count++;
        countSet.add(array[i]);
      } else {
        set.add(array[i]);
      }
    }
    System.out.println("countSet" + countSet.size());
    return count;
  }

  /**
   * 多次重复的只计数一次，且记录下重复的数字
   */
  public void findRepeatCount2(int array[]) {
    if (array == null || array.length <= 0) {
      System.out.println("数组为null或者数组的长度小于等于0");
      return;
    }

    Map<Integer, Integer> countMap = new HashMap();
    for (int i = 0; i < array.length; i++) {
      if (!countMap.keySet().contains(array[i])) {
        countMap.put(array[i], 1);
      } else {
        countMap.put(array[i], countMap.get(array[i]) + 1);
      }
    }

    for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
      if (entry.getValue() > 1) {
        System.out.println("重复的数字为" + entry.getKey() + "  重复的次数为" + entry.getValue());
      }
    }

  }


  public static void main(String args[]) {
    FindRepeatCount FindRepeatCount = new FindRepeatCount();
    int count = FindRepeatCount.findRepeatCount(new int[]{1, 2, 3, 4, 5, 6, 1, 2, 3, 1});
    System.out.println("重复数字的个数为" + count);

    FindRepeatCount.findRepeatCount2(new int[]{1, 2, 3, 4, 5, 6, 1, 2, 3, 1});
  }

}
